/*
 * KeyboardListener
 * 
 * Version information:1.0
 *
 * Date: 19/11/2012
 */
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JTextArea;
import javax.swing.JTextField;

public class KeyboardListener implements KeyListener {

    /*
     * A reference to a input-field where we will add or remove text
     * based on what input we get from user.
     */
    private JTextField input;

    /*
     * A reference to a textarea where results from MyUnitTester will
     * be added.
     */
    private JTextArea textArea;

    // An array of acceptable characters for input.
    private final static String[] availbleInput = ("A B C D E F G H I J K L"
	    + " M N O P Q R S T U V W X Y Z Å Ä Ö a b c d e f"
	    + " g h i j k l m n o p q r s t u v w x y z å ä ö 1"
	    + " 2 3 4 5 6 7 8 9 0 _ -").split(" ");

    /**
     * Store references to a GUI components used in the program
     * 
     * @param runInput
     * @param textArea
     */
    public KeyboardListener(JTextField runInput, JTextArea textArea) {
	if (runInput == null || textArea == null) {
	    throw new NullPointerException("JTextField and/or textArea is null");
	}
	this.input = runInput;
	this.textArea = textArea;
    }

    /**
     * When a keyEvent happens different actions are taken. if the
     * event is Enter we try to run the tests in the class. if the
     * event is back space we remove the last written letter. else we
     * try to see if a valid letter was entered.
     * 
     * @see KeyboardListener.availbleInput
     * @see java.awt.event.KeyListener#keyPressed(java.awt.event.KeyEvent)
     */
    /*
     * Notice that all letters is not supported, use JTextField if for
     * where all letters are acceptable.(non-Javadoc)
     * 
     * @see
     * java.awt.event.KeyListener#keyPressed(java.awt.event.KeyEvent)
     */
    @Override
    public void keyPressed(KeyEvent e) {

	boolean checkForLetter = true;
	if (e.getKeyCode() == KeyEvent.VK_ENTER) {
	    if (input.getText().length() > 0) {
		(new Thread(new MyUnitTester(input.getText(), textArea)))
			.start();
		checkForLetter = false;
	    }
	} else if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
	    if (input.getText().length() > 0) {
		input.setText(input.getText().substring(0,
			(input.getText().length() - 1)));
	    }
	    checkForLetter = false;
	}
	if (checkForLetter) {
	    for (String pos : availbleInput) {
		if (pos.toCharArray()[0] == e.getKeyChar()) {
		    input.setText(input.getText() + pos);
		    break;
		}
	    }
	}
    }

    /*
     * un-implemented Method
     */

    @Override
    public void keyReleased(KeyEvent arg0) {
    }

    /*
     * un-implemented Method
     */

    @Override
    public void keyTyped(KeyEvent arg0) {
    }

}
